<!DOCTYPE html>
<html class="dark">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta content="0" http-equiv="expires">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <title>聊天室</title>
    <script src="../js/jquery.3.2.1.min.js"></script>
    <!--    https://unpkg.com/vue@3.4.27/dist/vue.runtime.global.prod.js-->
    <!--    <script src="../js/vue.runtime.global.prod.js"></script>-->
    <script src="https://cdn.staticfile.net/vue/3.3.4/vue.global.prod.js"></script>
    <!--    //unpkg.com/@element-plus/icons-vue-->
    <script src="../js/element-plus-icon.iife.min.js"></script>
    <!-- import CSS -->
    <!--    https://unpkg.com/element-plus/dist/index.css-->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <!--    https://unpkg.com/element-plus/theme-chalk/dark/css-vars.css-->
    <link rel="stylesheet" href="../css/dark-css-vars.css">
    <!-- import JavaScript -->
    <script src="https://unpkg.com/element-plus@2.7.3/dist/index.full.js"></script>
    <style>
        :root {
            --font-size: 16px; /* 默认字体大小 */
        }

        * {
            font-size: var(--font-size);
            box-sizing: border-box; /* 更好的盒模型处理 */
        }

        .dark {
            /* 暗黑模式下的样式 */
            background-color: #000;
            color: #fff;
        }

        .dark .el-card {
            /* 暗黑模式下卡片组件的样式 */
            background-color: #222;
            color: #fff;
            border-color: #444;
        }

        .dark .message-entry {
            max-width: 60%; /* 最大宽度 */
            margin-bottom: 10px; /* 消息间距 */
            padding: 10px;
            border-radius: 10px; /* 圆角 */
            background-color: #000; /* 消息背景 */
            position: relative; /* 相对定位 */
            margin-right: auto; /* 左对齐 */
        }

        .dark .message-entry2 {
            max-width: 60%; /* 最大宽度 */
            margin-bottom: 10px; /* 消息间距 */
            padding: 10px;
            border-radius: 10px; /* 圆角 */
            background-color: #000; /* 消息背景 */
            position: relative; /* 相对定位 */
            margin-left: auto; /* 右对齐 */
        }

        .highlighted {
            border: 2px solid #409EFF; /* Element UI primary color */
            background-color: #f0f9ff; /* Lighter shade for background */
        }

        .dark .highlighted {
            border: 2px solid #5b8ff9; /* 暗模式下的边框颜色，稍亮以确保可见性 */
            background-color: #1f2d3d; /* 暗模式下的背景颜色，更暗的色调 */
            /*color: #c0c4cc; !* 暗模式下的文字颜色，如果有文字的话 *!*/
        }

        .announcement-section {
            padding: 10px;
            margin-bottom: 10px; /* 公告与聊天部分之间的间距 */
        }

        .announcement-card {
            background-color: #f9f9f9; /* 浅色背景，便于查看 */
            border: 1px solid #ccc; /* 细微边框 */
        }


        .app {
            display: flex;
            height: 100vh;
            border: 1px solid #ccc; /* 添加边框 */
        }

        .user-card {
            height: 80%;
            /*overflow-y: auto; !* 确保可以滚动 *!*/
            /*padding: 10px; !* 添加内边距 *!*/
            border-right: 1px solid #ccc; /* 分隔用户列表和聊天窗口 */
        }

        .custom-settings {
            height: 20%;
            padding: 10px; /* 添加内边距 */
            border-top: 1px solid #ccc;
            border-right: 1px solid #ccc; /* 分隔用户列表和聊天窗口 */
        }

        .chat-window {
            padding: 10px;
            display: flex;
            flex-direction: column; /* 方向改为列布局 */
            height: 100%;
        }

        .message-area {
            flex-grow: 1; /* 允许消息区域填满剩余空间 */
            overflow-y: auto;
            background-color: #f0f0f0; /* 背景色 */
            padding: 20px; /* 内边距 */
        }

        .message-entry {
            max-width: 60%; /* 最大宽度 */
            margin-bottom: 10px; /* 消息间距 */
            padding: 10px;
            border-radius: 10px; /* 圆角 */
            background-color: #fff; /* 消息背景 */
            position: relative; /* 相对定位 */
            margin-right: auto; /* 左对齐 */
            white-space: pre-wrap; /* 保留空格和换行符，并自动换行 */
        }

        .message-entry2 {
            max-width: 60%; /* 最大宽度 */
            margin-bottom: 10px; /* 消息间距 */
            padding: 10px;
            border-radius: 10px; /* 圆角 */
            background-color: #fff; /* 消息背景 */
            position: relative; /* 相对定位 */
            margin-left: auto; /* 右对齐 */
            white-space: pre-wrap; /* 保留空格和换行符，并自动换行 */
        }

        .message-content {
            max-width: 60%;
            background-color: white;
            padding: 8px;
            border-radius: 10px;
            border: 1px solid #ccc;
        }

        .avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            margin-left: 10px;
            margin-right: 10px;
            object-fit: cover;
        }

        .input-area {
            display: flex;
            margin-top: 10px; /* 输入区域和消息区域的间隔 */
        }

        .input-area el-input {
            flex-grow: 1; /* 输入框填满剩余空间 */
            margin-right: 10px; /* 输入框和按钮间的间隔 */
        }

        .slider-demo-block {
            max-width: 300px;
            display: flex;
            align-items: center;
        }

        .slider-demo-block .el-slider {
            margin-top: 0;
            margin-left: 12px;
        }

        /*.work {*/
        /*    display: none;*/
        /*}*/

        /*#server {*/
        /*    width: 400px;*/
        /*}*/
    </style>
</head>
<body>
<div id="loading"
     style="font-size: 30px; display: flex; align-items: center; justify-content: center; height: 100vh; background-color: #fff;">
    <!-- 加载动画 -->
    <div>加载中...</div>
</div>
<div id="app" style="display: none;">
    <div>
        <el-row class="app">
            <!-- 左侧 -->
            <el-col :span="4">
                <!-- 左侧在线用户列表 -->
                <el-row class="user-card">
                    <el-scrollbar height="80vh">
                        <el-badge :value="isChatAllDot? 'new' : ''" :offset="[-40, 10]">
                            <el-card shadow="hover" style="width: 32vh; height: 10vh; cursor: pointer;"
                                     :class="{ highlighted: toUser === null && toChannel === null }"
                                     @click="startPublicChat()">
                                <h1>群聊灌水</h1>
                            </el-card>
                        </el-badge>

                        <!-- 频道列表 -->
                        <el-divider content-position="center">频道列表</el-divider>
                        <el-dialog v-model="channelDialogVisible"
                                   title="新增频道"
                                   width="500"
                                   center
                                   align-center>
                            <el-form
                                    ref="ruleFormRef_channel"
                                    :model="channelForm"
                                    status-icon
                                    :rules="rules_channel">
                                <el-form-item prop="name">
                                    <el-input
                                            v-model="channelForm.name"
                                            clearable
                                            label="名称"
                                            width="200%"
                                            placeholder="请输入名称"></el-input>
                                </el-form-item>
                                <el-form-item prop="description">
                                    <el-input
                                            v-model="channelForm.description"
                                            type="textarea"
                                            clearable
                                            label="描述"
                                            width="200%"
                                            placeholder="请输入描述"></el-input>
                                </el-form-item>

                            </el-form>
                            <template #footer>
                                <div class="dialog-footer">
                                    <el-button @click="channelDialogVisible = false">取消</el-button>
                                    <el-button type="primary" @click="submitForm_channel(ruleFormRef_channel)">
                                        新增
                                    </el-button>
                                </div>
                            </template>
                        </el-dialog>

                        <div style="text-align: center;">
                            <el-tooltip
                                    content="新增频道"
                                    effect="light"
                                    placement="top"
                                    v-if="nickname"
                            >
                                <el-button type="primary" size="large" :icon="CirclePlus" circle
                                           @click.stop="addAChannel()">
                                </el-button>
                            </el-tooltip>
                        </div>


                        <el-empty v-if="channels.length === 0" description="暂无频道"></el-empty>
                        <div v-for="(channel, index) in channels" :key="channel.id">
                            <el-badge :value="isChatChannelDot[index]? 'new' : ''" :offset="[-40, 10]">
                                <el-card shadow="hover" style="width: 32vh; height: 30vh; cursor: pointer;"
                                         :class="{ highlighted: toChannel && toChannel.name === channel.name }"
                                         @click="startChannelChat(index, channel.name, channels.description)">
                                    <div style="display: flex; align-items: center;">
                                        <h4>{{ channel.name }}</h4>
                                    </div>

                                    <div>
                                        <el-row>
                                            <el-col :span="12">
                                                <template v-if="hasJoinChannel[index]">
                                                    <el-tag type="success">已加入</el-tag>
                                                </template>
                                                <template v-else>
                                                    <el-tag type="primary">未加入</el-tag>
                                                </template>
                                            </el-col>
                                            <el-col :span="12">
                                                <div style="padding-left: 5vh">
                                                    <el-popover placement="top" title="频道信息" width="240px"
                                                                trigger="hover">
                                                        <el-scrollbar max-height="30vh">
                                                            <!-- 频道板块 -->
                                                            <el-row class="announcement-section">
                                                                <el-col :span="24">
                                                                    <el-card class="announcement-card">
                                                                        <el-divider content-position="center">频道描述
                                                                        </el-divider>
                                                                        <el-empty size="small"
                                                                                  v-if="!channel.description"
                                                                                  description="暂无描述"></el-empty>
                                                                        <div>
                                                                            <el-text type="success">
                                                                                {{channel.description}}
                                                                            </el-text>
                                                                        </div>

                                                                        <el-divider content-position="center">频道用户
                                                                        </el-divider>
                                                                        <el-empty size="small"
                                                                                  v-if="channel.users.length === 0 || !channel.users"
                                                                                  description="暂无用户"></el-empty>
                                                                        <div v-for="nicknameItem in channel.users">
                                                                            <el-text type="primary">{{nicknameItem}}
                                                                            </el-text>

                                                                        </div>
                                                                    </el-card>
                                                                </el-col>
                                                            </el-row>
                                                        </el-scrollbar>

                                                        <template #reference>
                                                            <el-button :icon="More"></el-button>
                                                        </template>
                                                    </el-popover>
                                                </div>
                                            </el-col>
                                        </el-row>
                                    </div>

                                    <template v-if="roleName === '用户' || roleName === '管理员'">
                                        <template v-if="!hasJoinChannel[index]">
                                            <el-tooltip
                                                    content="加入频道"
                                                    effect="light"
                                                    placement="top"
                                            >
                                                <el-button type="success" :icon="Plus"
                                                           @click.stop="joinChannel(channel.name)">
                                                </el-button>
                                            </el-tooltip>
                                        </template>
                                        <template v-else>
                                            <el-tooltip
                                                    content="退出频道"
                                                    effect="light"
                                                    placement="top"

                                            >
                                                <el-button type="warning" :icon="Minus"
                                                           @click.stop="exitChannel(channel.name)">
                                                </el-button>
                                            </el-tooltip>
                                        </template>
                                    </template>

                                    <template v-if="roleName === '管理员'">
                                        <el-tooltip
                                                content="删除频道"
                                                effect="light"
                                                placement="top"
                                        >
                                            <el-button type="danger" :icon="Delete"
                                                       @click.stop="removeChannel(channel.name)">

                                            </el-button>
                                        </el-tooltip>

                                    </template>
                                    </template>


                                </el-card>
                            </el-badge>

                        </div>

                        <!-- 在线用户列表 -->
                        <el-divider content-position="center">用户列表</el-divider>
                        <el-empty v-if="onlineUsers.length === 0" description="暂无在线用户"></el-empty>
                        <div v-for="(user, index) in onlineUsers" :key="user.sessionId">
                            <el-badge :value="isChatPrivateDot[index]? 'new' : ''" :offset="[-40, 10]">
                                <el-card shadow="hover" style="width: 32vh; height: 30vh; cursor: pointer;"
                                         :class="{ highlighted: toUser && toUser.sessionId === user.sessionId }"
                                         @click="startPrivateChat(index, user.sessionId, user.cid)">
                                    <div style="display: flex; align-items: center;">
                                        <img src="../images/other.png" alt="Avatar"
                                             class="avatar">
                                        <div>
                                            <h4>{{ user.cid }}</h4>
                                            <el-tag size="small" type="primary">登录时间:</el-tag>
                                            <br/>
                                            <el-text size="small" type="primary">{{ user.loginTime }}</el-text>
                                            <br/>
                                            <el-text size="small" type="info">会话 ID: {{ user.sessionId }}
                                            </el-text>
                                        </div>


                                    </div>
                                    <div style="padding-left: 5vh">
                                        <template v-if="roleName === '管理员'">
                                            <template v-if="user.muted">
                                                <el-tooltip
                                                        content="解禁"
                                                        effect="light"
                                                        placement="top"

                                                >
                                                    <el-button type="success" :icon="Check"
                                                               @click.stop="sendCommand('unmute', user.cid)">
                                                    </el-button>
                                                </el-tooltip>
                                            </template>
                                            <template v-else>
                                                <el-tooltip
                                                        content="禁言"
                                                        effect="light"
                                                        placement="top"

                                                >
                                                    <el-button type="warning" :icon="Close"
                                                               @click.stop="sendCommand('mute', user.cid)">
                                                    </el-button>
                                                </el-tooltip>
                                            </template>

                                            <el-tooltip
                                                    content="踢出"
                                                    effect="light"
                                                    placement="top"
                                            >
                                                <el-button type="danger" :icon="Delete"
                                                           @click.stop="sendCommand('kick', user.cid, user.sessionId)">

                                                </el-button>
                                            </el-tooltip>

                                        </template>
                                    </div>
                                </el-card>
                            </el-badge>

                        </div>
                    </el-scrollbar>
                </el-row>

                <!-- 左下角的用户设置 -->
                <el-row class="custom-settings">
                    <div style="display: flex; align-items: center;">
                        <img v-if="nickname" src="../images/me.png" alt="Avatar"
                             class="avatar">
                        <img v-else src="../images/default_handsome.jpg" alt="Avatar"
                             class="avatar">
                        <div>
                            <h4>{{ nickname === '' ? '游客' : nickname }}</h4>
                        </div>
                        <!-- 状态显示 -->
                        <template v-if="nickname">
                            <el-tag v-if="isBeMuted" size="small" type="warning">被禁言</el-tag>
                            <el-tag v-else size="small" type="success">正常</el-tag>
                        </template>
                        <template v-else>
                            <el-tag size="small" type="warning">请登录</el-tag>
                        </template>

                    </div>
                    <el-dialog v-model="dialogVisible"
                               title="登录"
                               width="500"
                               center
                               align-center>
                        <el-form
                                ref="ruleFormRef"
                                :model="loginForm"
                                status-icon
                                :rules="rules">
                            <el-form-item label="角色">
                                <el-radio-group v-model="loginForm.roleName">
                                    <el-radio-button label="用户" value="用户"/>
                                </el-radio-group>
                                <el-radio-group v-model="loginForm.roleName">
                                    <el-radio-button label="管理员" value="管理员"/>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item prop="nickname">
                                <el-autocomplete
                                        v-model="loginForm.nickname"
                                        :fetch-suggestions="querySearch"
                                        clearable
                                        :prefix-icon="User"
                                        width="200%"
                                        placeholder="请输入昵称"></el-autocomplete>
                            </el-form-item>
                            <template v-if="loginForm.roleName === '管理员'">
                                <el-form-item
                                        prop="password"
                                >
                                    <el-input v-model="loginForm.password"
                                              autocomplete="off"
                                              type="password"
                                              :prefix-icon="Lock"
                                              show-password></el-input>
                                </el-form-item>
                            </template>
                        </el-form>
                        <template #footer>
                            <div class="dialog-footer">
                                <el-button @click="dialogVisible = false">取消</el-button>
                                <el-button type="primary" @click="submitForm(ruleFormRef)">
                                    登录
                                </el-button>
                            </div>
                        </template>
                    </el-dialog>
                    <div>
                        <template v-if="nickname !== ''">
                            <el-tooltip
                                    content="退出登录"
                                    effect="light"
                                    placement="top"
                            >

                                <el-button
                                        :icon="SwitchButton"
                                        circle
                                        @click="logout()"
                                ></el-button>
                            </el-tooltip>
                        </template>
                        <template v-else>
                            <el-tooltip
                                    content="登录"
                                    effect="light"
                                    placement="top"
                            >

                                <el-button
                                        :icon="User"
                                        circle
                                        @click="dialogVisible = true"
                                ></el-button>
                            </el-tooltip>
                        </template>

                        <el-tooltip
                                content="全屏"
                                effect="light"
                                placement="top"
                        >
                            <el-button
                                    :icon="FullScreen"
                                    circle
                                    @click="fullScreen"
                            ></el-button>
                        </el-tooltip>

                        <el-popover placement="top" title="字体大小" width="300px" trigger="hover">
                            <div class="slider-demo-block">
                                <el-slider size="small" v-model="fontSize" show-input/>
                            </div>

                            <el-text>暗黑模式</el-text>
                            <el-switch
                                    @change="changeDark"
                                    v-model="dark"
                                    class="mt-2"
                                    style="margin-left: 24px"
                                    inline-prompt
                                    :active-icon="MoonNight"
                                    :inactive-icon="Sunny"></el-switch>

                            <template #reference>
                                <el-button :icon="Setting" circle></el-button>
                            </template>
                        </el-popover>

                        <el-popover placement="top" title="公告" width="1200px" trigger="hover">
                            <el-scrollbar max-height="30vh">
                                <!-- 公告板块 -->
                                <el-row class="announcement-section">
                                    <el-col :span="24">
                                        <el-card class="announcement-card">
                                            <p>欢迎来到我们的聊天室！请保持礼貌。</p>
                                            <div v-for="ann in announcement">
                                                <div>
                                                    <el-text type="primary">{{ann.date}}</el-text>
                                                    <br/>
                                                    <el-text>{{ann.content}}</el-text>
                                                </div>
                                            </div>
                                        </el-card>
                                    </el-col>
                                </el-row>
                            </el-scrollbar>


                            <template #reference>
                                <el-button :icon="Bell" circle></el-button>
                            </template>
                        </el-popover>

                        <el-popover placement="top" title="日志" width="1200px" trigger="hover">
                            <!-- 日志板块 -->
                            <el-scrollbar max-height="30vh">
                                <el-row class="announcement-section">
                                    <el-col :span="24">
                                        <el-card class="announcement-card">
                                            <div v-for="msgLog in messageLog">
                                                <el-text>{{msgLog}}</el-text>
                                            </div>
                                        </el-card>
                                    </el-col>
                                </el-row>
                            </el-scrollbar>


                            <template #reference>
                                <el-button :icon="Postcard" circle></el-button>
                            </template>
                        </el-popover>


                    </div>

                </el-row>
            </el-col>


            <!-- 右侧聊天窗口 -->
            <el-col :span="20" class="chat-window">
                <el-card class="message-area">
                    <el-empty v-if="chatMessages.length === 0" description="暂无消息"></el-empty>
                    <template v-else>
                        <div style="text-align: center;">
                            <template v-if="hasMoreMessage">
                                <el-link type="primary" size="small" @click="seeMoreMessage">查看更多消息</el-link>
                            </template>
                            <template v-else>
                                <el-text type="info" size="small">没有更多消息</el-text>
                            </template>
                        </div>

                        <div v-for="msg in chatMessages" :key="msg.id">
                            <!-- 我的消息 -->
                            <template v-if="msg.senderId === nickname">
                                <div style="display: flex; align-items: center; justify-content: flex-end;">
                                    <div>
                                        <div>
                                            <el-text size="small" type="info">{{ msg.senderId }}</el-text>
                                            <el-tag size="small" type="primary">{{msg.timestamp}}</el-tag>
                                        </div>
                                        <p class="message-entry2">{{ msg.content }}</p>
                                    </div>
                                    <img class="avatar" src="../images/me.png"
                                         alt="user avatar">
                                </div>
                            </template>
                            <!-- 对方的消息 -->
                            <template v-else>
                                <div style="display: flex; align-items: center;">
                                    <img class="avatar" src="../images/other.png"
                                         alt="user avatar">
                                    <div>
                                        <div>
                                            <el-text size="small" type="info">{{ msg.senderId }}</el-text>
                                            <el-tag size="small" type="primary">{{msg.timestamp}}</el-tag>
                                        </div>
                                        <p class="message-entry">{{ msg.content }}</p>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </template>
                </el-card>
                <div class="input-area">
                    <el-col :span="22">
                        <el-input
                                v-model="message"
                                style="width: 100%"
                                :autosize="{ minRows: 3, maxRows: 27 }"
                                type="textarea"
                                placeholder="输入消息..."
                                :disabled="nickname === '' || isBeMuted"></el-input>
                    </el-col>


                    <el-dropdown split-button
                                 type="primary"
                                 :icon="Position"
                                 trigger="click"
                                 :disabled="nickname === '' || isBeMuted"
                                 @command="changeSendMessageMethod"
                                 @click="sendmessage">
                        发送
                        <template #dropdown>
                            <el-dropdown-menu>
                                <template v-if="sendMessageMethod === 'enter'">
                                    <el-dropdown-item :icon="Check" command="enter">按Enter发送</el-dropdown-item>
                                    <el-dropdown-item command="ctrl">按Ctrl+Enter发送</el-dropdown-item>
                                </template>
                                <template v-else>
                                    <el-dropdown-item command="enter">按Enter发送</el-dropdown-item>
                                    <el-dropdown-item :icon="Check" command="ctrl">按Ctrl+Enter发送</el-dropdown-item>
                                </template>

                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </el-col>
        </el-row>

    </div>
    <!--            <el-button @click="selectAllMessage">聊天记录</el-button>-->

    <!--            <el-button @click="getOnlineUsers">Get Online Users</el-button>-->
    <!--    <el-input v-model="server" placeholder="Enter your WebSocket server URL"></el-input>-->
    <!--    <el-input v-model="nickname" placeholder="Enter your nickname"></el-input>-->

    <!--    <el-button @click="closeWebsocket">Close</el-button>-->


    <!--    <el-button @click="openWebsocket">Connect</el-button>-->


    <!--    <el-input v-model="message" placeholder="Enter message to send"></el-input>-->
    <!--    <el-button @click="sendmessage">Send Message</el-button>-->
    <!--    <el-button @click="sendCommand('mute', 'bobydog')">禁言</el-button>-->
    <!--    <el-button @click="sendCommand('unmute', 'bobydog')">解除禁言</el-button>-->
    <!--    <el-button @click="sendCommand('kick', 'bobydog')">踢出</el-button>-->
    <!--    <el-button @click="getAllChannel">获取所有频道</el-button>-->
    <!--    <el-text v-for="(item, index) in channels"></el-text>-->
    <!--    <el-button @click="addAChannel">增加一个频道</el-button>-->

</div>
<script type="module">
    import {baseUrl} from "./baseUrl.js";

    const {ref, onBeforeMount, watch, onMounted, onUnmounted} = Vue; // 从 Vue 全局对象解构出 ref
    const {ElNotification} = ElementPlus;
    const {
        Position,
        FullScreen,
        User,
        Setting,
        MoonNight,
        Sunny,
        Bell,
        Postcard,
        Check,
        Plus,
        Minus,
        Close,
        Delete,
        SwitchButton,
        Lock,
        CirclePlus,
        More
    } = ElementPlusIconsVue;
    const App = {
            setup() {
                // const server = ref('ws://localhost:8080/websocket/');
                const server = ref('');
                const nickname = ref('');
                const announcement = ref([]); // 默认或动态公告
                const message = ref('');
                const sendMessageMethod = ref('enter');
                const messageLog = ref([]);
                const websocket = ref(null);
                const onlineUsers = ref([]); // 在线用户列表
                const chatMessages = ref([]); // 聊天记录
                const dialogVisible = ref(true); // 是否显示登录对话框
                const fontSize = ref(16); // 暗黑模式
                const roleName = ref('游客');
                const toUser = ref(null); // 私聊对象
                const toChannel = ref(null); // 频道对象
                const isChatAllDot = ref(false); // 是否显示聊天窗口的未读消息
                const isChatPrivateDot = ref([]); // 是否显示私聊窗口的未读消息
                const isChatChannelDot = ref([]); // 是否显示频道窗口的未读消息
                const isBeMuted = ref(false); // 是否被禁言
                const dark = ref(true); // 暗黑模式的开关
                const loginForm = ref({
                    roleName: '用户',
                    nickname: '',
                    password: '111111'
                })
                const someNickname = ref([
                    {
                        value: '孟令涛',
                    },
                    {
                        value: 'bobydog',
                    },
                    {
                        value: 'admin',
                    }
                ]);
                const ruleFormRef = ref()
                // 表单校验规则
                const rules = ref({
                    nickname: [
                        {required: true, message: '请输入昵称', trigger: 'blur'},
                        {min: 1, max: 15, message: '昵称应在1-15位之间', trigger: 'blur'},
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 3, max: 15, message: '密码应在3-15位之间', trigger: 'blur'},
                    ],
                });
                const ruleFormRef_channel = ref()
                // 表单校验规则
                const rules_channel = ref({
                    name: [
                        {required: true, message: '请输入频道名称', trigger: 'blur'},
                        {min: 1, max: 15, message: '频道名称应在1-15位之间', trigger: 'blur'},
                    ],
                });
                // 设置默认的分页参数
                let pageNum = 1; // 默认为第一页
                let pageSize = 5; // 默认每页显示10条记录
                let isClickMoreMessage = false; // 是否点击了加载更多消息
                const hasMoreMessage = ref(true); // 是否有更多消息
                const channels = ref([]) // 所有频道
                // 频道表单
                const channelForm = ref({
                    name: '',
                    description: ''
                })
                const channelDialogVisible = ref(false)
                const hasJoinChannel = ref([])
                const intervalId = ref(null)

                // 获取 WebSocket 服务器地址
                const getWebSocketServer = () => {
                    $.ajax({
                        url: baseUrl + '/hello/websocket-url/server',
                        method: 'GET',
                        async: false,
                        success: function (data) {
                            server.value = data;
                        },
                        error: function (error) {
                            console.error('Error fetching WebSocket URL:', error);
                            server.value = 'ws://localhost:8080/websocket/';
                        }
                    });
                }

                onBeforeMount(() => {
                    getWebSocketServer();
                    getAllChannel()
                });

                const handleKeydown = (event) => {
                    switch (sendMessageMethod.value) {
                        case 'enter':
                            if (event.key === 'Enter') {
                                if (!event.shiftKey) {
                                    event.preventDefault();  // 防止默认行为，如浏览器书签页的打开
                                    sendmessage();
                                }
                                // 如果按下 Shift+Enter，不做任何处理，允许换行
                            }
                            break
                        case 'ctrl':
                            if (event.ctrlKey && event.key === 'Enter') {
                                event.preventDefault();  // 防止默认行为，如浏览器书签页的打开
                                sendmessage();
                            }
                            break
                        default:
                            break
                    }
                };

                onMounted(() => {
                    window.addEventListener('keydown', handleKeydown);
                    document.getElementById('loading').style.display = 'none';
                    document.getElementById('app').style.display = ''; // 显示主内容
                });

                onUnmounted(() => {
                    window.removeEventListener('keydown', handleKeydown);
                });

                // 使用 watch 来监听 fontSize 的变化
                watch(fontSize, (newValue) => {
                    // 当 fontSize 变化时，更新 :root 的 --font-size 变量
                    document.documentElement.style.setProperty('--font-size', `${newValue}px`);
                });

                // 使用 watch 来监听 toUser 的变化，即聊天对象的变化
                watch(toUser, (newValue) => {
                    if (newValue) {
                        toChannel.value = null
                    }

                    // 是否有更多消息返回初始化状态
                    hasMoreMessage.value = true;

                    // 分页回到第一页
                    pageNum = 1;

                    // 清空现有消息
                    chatMessages.value = [];

                    // 查找消息记录
                    selectAllMessage();
                });

                // 使用 watch 来监听 toChannel 的变化，即频道的变化
                watch(toChannel, (newValue) => {
                    if (newValue) {
                        toUser.value = null
                    }

                    // 是否有更多消息返回初始化状态
                    hasMoreMessage.value = true;

                    // 分页回到第一页
                    pageNum = 1;

                    // 清空现有消息
                    chatMessages.value = [];

                    // 查找消息记录
                    selectAllMessage();
                });

                const appendMessage = (s) => {
                    // messageLog.value += `\n${new Date()}：${s}`;
                    messageLog.value.push(`${new Date()}：${s}`);
                };


                class WebSocketMessage {
                    constructor(type, cid, toSessionId, toChannelName, content, message) {
                        this.type = type;
                        this.cid = cid;
                        this.toSessionId = toSessionId;
                        this.toChannelName = toChannelName;
                        this.content = content;
                        this.message = message;
                    }

                    static fromJson(jsonString) {
                        let data = JSON.parse(jsonString);
                        return new WebSocketMessage(
                            data.type,
                            data.cid,
                            data.toSessionId,
                            data.toChannelName,
                            data.content,
                            data.message,
                        );
                    }
                }

                const openWebsocket = () => {
                    const wsUrl = server.value + nickname.value;
                    websocket.value = new WebSocket(wsUrl);
                    websocket.value.onopen = () => {
                        appendMessage("Connection open ...");
                    };
                    websocket.value.onmessage = async (evt) => {
                        appendMessage(`Received Message: ${evt.data}`);

                        if (evt.data === 'ping') {
                            // 不做任何事
                        } else if (evt.data.startsWith('错误：该ID已在聊天室中，')) {
                            ElNotification({
                                title: '登录失败！与在线用户的昵称重复！',
                                message: evt.data,
                                type: 'error',
                                duration: 0, // 不会自动关闭
                            })
                            roleName.value = '游客'
                        } else if (evt.data.startsWith('欢迎光临本站，您好：')) {
                            ElNotification({
                                title: '登录成功',
                                message: evt.data,
                                type: 'success',
                            })
                        } else if (evt.data.startsWith('{') && evt.data.endsWith('}')) {
                            let webSocketMessage = WebSocketMessage.fromJson(evt.data);

                            switch (webSocketMessage?.type) {
                                case 'notification': // 其他通知
                                {

                                    announcement.value.push(
                                        {
                                            content: webSocketMessage.message,
                                            date: new Date()
                                        }
                                    )

                                    getOnlineUsers()

                                    break;
                                }

                                case 'close':
                                    announcement.value.push(
                                        {
                                            content: webSocketMessage.message,
                                            date: new Date()
                                        }
                                    )
                                    getOnlineUsers();
                                    if (toUser.value.cid === webSocketMessage.cid) { // 如果被下线的用户是当前用户
                                        toUser.value = null;
                                        selectAllMessage();
                                    }
                                    break;
                                case 'mute': // 禁言
                                    announcement.value.push(
                                        {
                                            content: webSocketMessage.message,
                                            date: new Date()
                                        }
                                    )
                                    if (webSocketMessage.cid === nickname.value) {
                                        isBeMuted.value = true;
                                        ElNotification({
                                            title: '您已被禁言',
                                            message: webSocketMessage.message,
                                            type: 'warning',
                                            duration: 0, // 不会自动关闭
                                        })
                                    }
                                    getOnlineUsers()
                                    break;
                                case 'unmute': // 解禁
                                    announcement.value.push(
                                        {
                                            content: webSocketMessage.message,
                                            date: new Date()
                                        }
                                    )
                                    if (webSocketMessage.cid === nickname.value) {
                                        isBeMuted.value = false;
                                        ElNotification({
                                            title: '您已被解除禁言',
                                            message: webSocketMessage.message,
                                            type: 'success',
                                            duration: 0, // 不会自动关闭
                                        })
                                    }
                                    getOnlineUsers()
                                    break;
                                case 'kick': // 踢出
                                    announcement.value.push(
                                        {
                                            content: webSocketMessage.message,
                                            date: new Date()
                                        }
                                    )
                                    getOnlineUsers()
                                    if (toUser.value?.cid === webSocketMessage?.cid) { // 如果被踢出的用户是当前用户
                                        toUser.value = null;
                                        selectAllMessage();
                                    }
                                    break;
                                case 'private':
                                    for (let i = 0; i < onlineUsers.value.length; i++) {
                                        if (onlineUsers.value[i].cid === webSocketMessage.cid) {
                                            isChatPrivateDot.value[i] = true;
                                        }
                                    }

                                    selectAllMessage();
                                    break;
                                case 'public':
                                    if (toUser) {
                                        isChatAllDot.value = true;
                                    }

                                    selectAllMessage();
                                    break;

                                case 'channel':
                                    for (let i = 0; i < channels.value.length; i++) {
                                        if (channels.value[i].name === webSocketMessage.toChannelName) {
                                            isChatChannelDot.value[i] = true;
                                        }
                                    }

                                    selectAllMessage();
                                    break;
                                case 'command_private':
                                    selectAllMessage();
                                    break;
                                case 'command_channel':
                                    selectAllMessage();
                                    break;
                                case 'command_public':
                                    break;
                                case 'changeChannel':
                                    getAllChannel()
                                    break;
                                default:
                                    selectAllMessage();
                                    break;
                            }
                        }

                    }

                    websocket.value.onclose = (evt) => {
                        // 如果已经登录
                        if (nickname.value !== '' && evt.reason !== 'CID已存在') {
                            ElNotification({
                                title: '您已被踢出本站',
                                type: 'error',
                                duration: 0, // 不会自动关闭
                            })
                        }
                        appendMessage("Connection closed.");

                        // getOnlineUsers()
                        // 清空在线用户列表
                        onlineUsers.value = [];
                        // 清空消息列表
                        chatMessages.value = [];

                        nickname.value = '';
                        channels.value = []
                        stopTimer()
                    };

                };

                const closeWebsocket = () => {
                    sendCommand('logout', nickname.value);
                    nickname.value = '';
                    channels.value = []
                    roleName.value = '游客'
                    ElNotification({
                        title: '退出登录成功！',
                        type: 'success',
                    })
                    websocket.value.close();
                };

                const changeSendMessageMethod = (command) => {
                    sendMessageMethod.value = command
                }
                const sendmessage = async () => {
                    if (message.value === '') { // 如果消息为空
                        return
                    }
                    // await addMessage();
                    addMessage().then(() => {
                        let msg = {
                            type: toUser.value === null ? 'command_public' : 'command_private',
                            toSessionId: toUser.value?.sessionId,
                            toChannelName: toChannel.value?.name,
                            cid: toUser.value?.cid,
                            content: message.value,
                        }

                        if (toChannel.value) {
                            msg.type = 'command_channel'
                        }

                        websocket.value.send(JSON.stringify(msg));

                        message.value = '';

                        // 是否有更多消息返回初始化状态
                        hasMoreMessage.value = true;

                        // 分页回到第一页
                        pageNum = 1;

                        // 清空现有消息
                        chatMessages.value = [];

                        // selectAllMessage();
                    })


                };

                const getOnlineUsers = () => {
                    $.ajax({
                        type: 'get',
                        url: baseUrl + '/hello/online-users',//uri，后台
                        // data: {id: id},//json格式的数据
                        dataType: 'json',
                        async: false,//是否异步，默认为true，可不写，如为false，前端会等url请求完毕才能执行其它任务
                        success: function (data) {//回调函数，调用执行成功后的回调函数
                            // alert(JSON.stringify(data));
                            if (data.length !== 0) {
                                data = data.filter(user => {
                                    return user.cid !== nickname.value;
                                });

                                onlineUsers.value = data;
                            }
                        },
                        error: function (xhr, textStatus, errorThrown) {//回调函数，调用执行失败后的回调函数
                            console.log(xhr);
                            console.log(textStatus);
                            console.log(errorThrown);
                        }
                    });
                };

                const addMessage = () => {
                    let data = {
                        senderId: nickname.value,
                        receiverId: toUser.value === null ? '' : toUser.value.cid,
                        toChannelName: toChannel.value === null ? '' : toChannel.value.name,
                        content: message.value
                    };
                    return $.ajax({
                        type: 'post',
                        url: baseUrl + '/hello/message/add',//uri，后台
                        data: JSON.stringify(data), //传复杂数据必须用JSON.stringify
                        contentType: "application/json;charset=utf-8", //传复杂数据必须用
                        async: false,//是否异步，默认为true，可不写，如为false，前端会等url请求完毕才能执行其它任务
                        success: function (data, xhr, textStatus, errorThrown) {//回调函数，调用执行成功后的回调函数
                            // if (data.length !== 0) {
                            //     onlineUsers.value = data;
                            // }
                        },
                        error: function (xhr, textStatus, errorThrown) {//回调函数，调用执行失败后的回调函数
                            console.log(xhr);
                            console.log(textStatus);
                            console.log(errorThrown);
                        }
                    });
                };

                const selectAllMessage = () => {
                    let myCid = nickname.value;
                    let otherCid = toUser.value === null ? '' : toUser.value?.cid;
                    let toChannelName = toChannel.value === null ? '' : toChannel.value.name;

                    return $.ajax({
                        type: 'get',
                        url: `${baseUrl}/hello/message/selectAll?senderId=${myCid}&receiverId=${otherCid}&toChannelName=${toChannelName}&pageNum=${pageNum}&pageSize=${pageSize}`,//uri，后台
                        // data: {id: id},//json格式的数据
                        dataType: 'json',
                        async: false,//是否异步，默认为true，可不写，如为false，前端会等url请求完毕才能执行其它任务
                        success: function (data) {//回调函数，调用执行成功后的回调函数
                            if (isClickMoreMessage) {
                                // 处理分页信息
                                if (data.nextPage === 0) { // 如果没有下一页
                                    hasMoreMessage.value = false; // 禁止加载更多
                                }

                                let tempMessage = []; // 临时存储消息
                                tempMessage = data.list; // 分页后，消息在data.list中
                                tempMessage.forEach((message) => {
                                    const dateString = message.timestamp;
                                    const date = new Date(dateString);
                                    message.timestamp = date.toLocaleString();
                                })
                                tempMessage.reverse(); // 翻转数组，将最新的消息放在最前面

                                // 将tempMessage中的每个消息逐个添加到chatMessages.value中
                                chatMessages.value.unshift(...tempMessage);
                            } else {
                                chatMessages.value = [];
                                let tempMessage = []; // 临时存储消息
                                tempMessage = data.list; // 分页后，消息在data.list中
                                tempMessage.forEach((message) => {
                                    const dateString = message.timestamp;
                                    const date = new Date(dateString);
                                    message.timestamp = date.toLocaleString();
                                })
                                tempMessage.reverse(); // 翻转数组，将最新的消息放在最前面

                                // 将tempMessage中的每个消息逐个添加到chatMessages.value中
                                chatMessages.value.push(...tempMessage);
                            }


                        },
                        error: function (xhr, textStatus, errorThrown) {//回调函数，调用执行失败后的回调函数
                            console.log(xhr);
                            console.log(textStatus);
                            console.log(errorThrown);
                        }
                    });
                };

                const loginAPI = () => {
                    const data = {
                        nickname: loginForm.value.nickname,
                        password: loginForm.value.roleName === '管理员' ? loginForm.value.password : ''
                    }
                    return new Promise((resolve, reject) => {
                        $.ajax({
                            type: 'post',
                            url: baseUrl + '/hello/user/login',//uri，后台
                            data: JSON.stringify(data), //传复杂数据必须用JSON.stringify
                            contentType: "application/json;charset=utf-8", //传复杂数据必须用
                            async: false,//是否异步，默认为true，可不写，如为false，前端会等url请求完毕才能执行其它任务
                            success: function (data, xhr, textStatus, errorThrown) {//回调函数，调用执行成功后的回调函数
                                if (data.code === 200) { // 注意：比较的是数字200，原代码中是字符串'200'
                                    resolve(data); // 当code为200时，解析Promise
                                } else {
                                    ElNotification({
                                        title: '登录失败！密码错误！',
                                        message: data.message,
                                        type: 'error',
                                        duration: 0, // 不会自动关闭
                                    })

                                    reject(new Error('登录未成功，code不是200')); // 否则，拒绝Promise
                                }
                            },
                            error: function (xhr, textStatus, errorThrown) {//回调函数，调用执行失败后的回调函数
                                reject(errorThrown || textStatus); // 在出错时也拒绝Promise
                            }
                        });
                    });
                }

                const login = () => {
                    loginAPI().then(() => {
                        openWebsocket();
                        if (nickname.value !== "") { // 如果登录成功
                            selectAllMessage(); // 获取消息
                        }
                        getAllChannel()
                        startTimer()
                    }).catch(error => { // 处理任何错误情况
                        // console.error("登录过程中发生错误:", error);
                    });

                }

                const sendCommand = (command, cid, toSessionId = "a") => {
                    let msg = {
                        type: command,
                        toSessionId: toSessionId,
                        cid: cid,
                        content: "",
                    }
                    try {
                        websocket.value.send(JSON.stringify(msg));
                    } catch (e) {
                        ElNotification({
                            title: '提示',
                            message: '请先登录！',
                            type: 'warning',
                        })
                    }

                }

                //全屏按钮点击的回调
                const fullScreen = () => {
                    //DOM对象的一个属性:可以用来判断当前是不是全屏模式[全屏:true,不是全屏:false]
                    let full = document.fullscreenElement
                    //切换为全屏模式
                    if (!full) {
                        //文档根节点的方法requestFullscreen,实现全屏模式
                        document.documentElement.requestFullscreen()
                    } else {
                        //变为不是全屏模式->退出全屏模式
                        document.exitFullscreen()
                    }
                }

                const startPublicChat = () => {
                    if (nickname.value) {
                        toUser.value = null;
                        toChannel.value = null;
                        isChatAllDot.value = false;
                    } else {
                        ElNotification({
                            title: '提示',
                            message: '请先登录！',
                            type: 'warning',
                        })
                    }
                }

                const startPrivateChat = (index, sessionId, cid) => {
                    toUser.value = {
                        sessionId: sessionId,
                        cid: cid
                    };
                    isChatPrivateDot.value[index] = false;
                }

                const startChannelChat = (index, name, description) => {
                    if (!hasJoinChannel.value[index]) { // 如果未加入
                        ElNotification({
                            title: '提示',
                            message: '请先加入频道！',
                            type: 'warning',
                        })
                        return
                    }
                    toChannel.value = {
                        name: name,
                        description: description
                    };
                    isChatChannelDot.value[index] = false;
                }

                //switch开关的chang事件进行暗黑模式的切换
                const changeDark = () => {
                    //获取HTML根节点
                    let html = document.documentElement
                    //判断HTML标签是否有类名dark
                    dark.value ? (html.className = 'dark') : (html.className = '')
                }

                // 昵称的自动补全输入框的方法
                const createFilter = (queryString) => {
                    return (someNickname) => {
                        return (
                            someNickname.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
                        )
                    }
                }

                // 昵称的自动补全输入框的方法
                const querySearch = (queryString, cb) => {
                    const results = queryString
                        ? someNickname.value.filter(createFilter(queryString))
                        : someNickname.value
                    // call callback function to return suggestions
                    cb(results)
                }

                const submitForm = async (formEl) => {
                    if (!formEl) return
                    await formEl.validate((valid, fields) => {
                        if (valid) {
                            if (loginForm.value.roleName === '管理员') {
                                if (loginForm.value.password === '111111') { // 检查密码是否正确
                                    roleName.value = loginForm.value.roleName;
                                    nickname.value = loginForm.value.nickname;
                                    login()
                                    dialogVisible.value = false;
                                } else {
                                    ElNotification({
                                        title: '密码错误！',
                                        message: '您的密码输入错误，请重新输入！',
                                        type: 'error',
                                    })
                                }
                            } else {
                                roleName.value = loginForm.value.roleName;
                                nickname.value = loginForm.value.nickname;
                                login()
                                dialogVisible.value = false;
                            }
                        } else {
                            ElNotification({
                                title: '请填写完整表单！',
                                message: '请仔细检查表单是否填写完整！',
                                type: 'warning',
                            })
                        }
                    })
                }

                // 提交新增频道表单
                const submitForm_channel = async (formEl) => {
                    if (!formEl) return
                    await formEl.validate((valid, fields) => {
                        if (valid) {
                            addAChannelAPI()
                            channelDialogVisible.value = false
                            sendCommand('command_changeChannel', nickname.value);
                        } else {
                            ElNotification({
                                title: '请填写完整表单！',
                                message: '请仔细检查表单是否填写完整！',
                                type: 'warning',
                            })
                        }
                    })
                }

                const logout = () => {
                    stopTimer()
                    closeWebsocket()
                }

                // 查看更多消息
                const seeMoreMessage = () => {
                    isClickMoreMessage = true;
                    pageNum++;
                    selectAllMessage().then(() => {
                        isClickMoreMessage = false;
                    })
                }

                const getAllChannelAPI = () => {
                    $.ajax({
                        type: 'get',
                        url: baseUrl + '/hello/channel/getAllChannel',//uri，后台
                        // data: {id: id},//json格式的数据
                        dataType: 'json',
                        async: false,//是否异步，默认为true，可不写，如为false，前端会等url请求完毕才能执行其它任务
                        success: function (data) {//回调函数，调用执行成功后的回调函数
                            if (data.code === 200) {
                                channels.value = data.data;
                            }
                        },
                        error: function (xhr, textStatus, errorThrown) {//回调函数，调用执行失败后的回调函数
                            console.log(xhr);
                            console.log(textStatus);
                            console.log(errorThrown);
                        }
                    });
                }

                const getAllUserByChannelNameAPI = (channelItem) => {
                    const channelName = channelItem.name
                    $.ajax({
                        type: 'get',
                        url: `${baseUrl}/hello/channel/getAllUserByChannelName?channelName=${channelName}`,//uri，后台
                        // data: {id: id},//json格式的数据
                        dataType: 'json',
                        async: false,//是否异步，默认为true，可不写，如为false，前端会等url请求完毕才能执行其它任务
                        success: function (data) {//回调函数，调用执行成功后的回调函数
                            if (data.code === 200) {
                                channelItem.users = data.data;
                            }
                        },
                        error: function (xhr, textStatus, errorThrown) {//回调函数，调用执行失败后的回调函数
                            console.log(xhr);
                            console.log(textStatus);
                            console.log(errorThrown);
                        }
                    });
                }

                // 获取所有频道
                const getAllChannel = () => {
                    getAllChannelAPI()
                    channels.value.forEach(channelItem => {
                        getAllUserByChannelNameAPI(channelItem)
                    })
                    solveHasJoinChannel() //  查找所有的加入的频道
                }

                const addAChannelAPI = () => {
                    const data = {
                        name: channelForm.value.name,
                        description: channelForm.value.description,
                    }
                    $.ajax({
                        type: 'post',
                        url: baseUrl + '/hello/channel/add',//uri，后台
                        data: JSON.stringify(data), //传复杂数据必须用JSON.stringify
                        contentType: "application/json;charset=utf-8", //传复杂数据必须用
                        async: false,//是否异步，默认为true，可不写，如为false，前端会等url请求完毕才能执行其它任务
                        success: function (data, xhr, textStatus, errorThrown) {//回调函数，调用执行成功后的回调函数
                            if (data.code === 200) {
                                getAllChannel(); // 获取所有频道
                                ElNotification({
                                    title: '添加频道成功！',
                                    message: data.message,
                                    type: 'success',
                                })
                            } else if (data.code === 202) {
                                ElNotification({
                                    title: '频道名已存在！',
                                    message: data.message,
                                    type: 'warning',
                                })
                            }
                        },
                        error: function (xhr, textStatus, errorThrown) {//回调函数，调用执行失败后的回调函数
                            console.log(xhr);
                            console.log(textStatus);
                            console.log(errorThrown);
                        }
                    });
                }

                const addAChannel = () => {
                    channelDialogVisible.value = true
                }

                const joinChannelAPI = (channelName) => {
                    const data = {
                        nickname: nickname.value,
                        channelName: channelName,
                    }
                    $.ajax({
                        type: 'post',
                        url: baseUrl + '/hello/channel/joinChannel',//uri，后台
                        data: JSON.stringify(data), //传复杂数据必须用JSON.stringify
                        contentType: "application/json;charset=utf-8", //传复杂数据必须用
                        async: false,//是否异步，默认为true，可不写，如为false，前端会等url请求完毕才能执行其它任务
                        success: function (data, xhr, textStatus, errorThrown) {//回调函数，调用执行成功后的回调函数
                            if (data.code === 200) {
                                getAllChannel(); // 获取所有频道
                                ElNotification({
                                    title: '加入频道成功！',
                                    message: data.message,
                                    type: 'success',
                                })
                            }
                        },
                        error: function (xhr, textStatus, errorThrown) {//回调函数，调用执行失败后的回调函数
                            console.log(xhr);
                            console.log(textStatus);
                            console.log(errorThrown);
                        }
                    });
                }

                const joinChannel = (channelName) => {
                    joinChannelAPI(channelName)
                }

                const solveHasJoinChannel = () => {
                    hasJoinChannel.value = []
                    channels.value.forEach(channelItem => {
                            let isJoin = false
                            channelItem.users.forEach((item) => {
                                if (nickname.value === item) {
                                    isJoin = true
                                }
                            })
                            hasJoinChannel.value.push(isJoin)

                        }
                    )
                }

                const exitChannelAPI = (channelName) => {
                    const data = {
                        nickname: nickname.value,
                        channelName: channelName,
                    }

                    $.ajax({
                        type: 'post',
                        url: baseUrl + '/hello/channel/exitChannel',//uri，后台
                        data: JSON.stringify(data), //传复杂数据必须用JSON.stringify
                        contentType: "application/json;charset=utf-8", //传复杂数据必须用
                        async: false,//是否异步，默认为true，可不写，如为false，前端会等url请求完毕才能执行其它任务
                        success: function (data, xhr, textStatus, errorThrown) {//回调函数，调用执行成功后的回调函数
                            if (data.code === 200) {
                                getAllChannel(); // 获取所有频道
                                ElNotification({
                                    title: '退出频道成功！',
                                    message: data.message,
                                    type: 'success',
                                })
                            }
                        },
                        error: function (xhr, textStatus, errorThrown) {//回调函数，调用执行失败后的回调函数
                            console.log(xhr);
                            console.log(textStatus);
                            console.log(errorThrown);
                        }
                    });
                }

                const exitChannel = (channelName) => {
                    exitChannelAPI(channelName)
                    if (channelName === toChannel.value.name) {
                        toChannel.value = null
                    }
                }

                const removeChannelAPI = (channelName) => {
                    $.ajax({
                        type: 'post',
                        url: baseUrl + '/hello/channel/removeChannel',//uri，后台
                        // data: JSON.stringify(channelName), //传复杂数据必须用JSON.stringify
                        data: channelName,
                        contentType: "application/json;charset=utf-8", //传复杂数据必须用
                        async: false,//是否异步，默认为true，可不写，如为false，前端会等url请求完毕才能执行其它任务
                        success: function (data, xhr, textStatus, errorThrown) {//回调函数，调用执行成功后的回调函数
                            if (data.code === 200) {
                                getAllChannel(); // 获取所有频道
                                ElNotification({
                                    title: '删除频道成功！',
                                    message: data.message,
                                    type: 'success',
                                })
                            }
                        },
                        error: function (xhr, textStatus, errorThrown) {//回调函数，调用执行失败后的回调函数
                            console.log(xhr);
                            console.log(textStatus);
                            console.log(errorThrown);
                        }
                    });
                }

                const removeChannel = (channelName) => {
                    removeChannelAPI(channelName)
                    if (channelName === toChannel.value.name) {
                        toChannel.value = null
                    }
                    sendCommand('command_changeChannel', nickname.value);
                }

                // 和心跳检测有关的代码
                const startTimer = () => {
                    intervalId.value = setInterval(() => {
                        try {
                            if (websocket.value && websocket.value.readyState === WebSocket.OPEN) {
                                websocket.value.send('ping');
                            } else {
                                throw new Error('WebSocket is not open');
                            }
                        } catch (e) {
                            // 关闭定时器
                            stopTimer();
                            // 提示错误
                            ElNotification({
                                title: '连接断开',
                                message: '连接断开，请检查网络连接后刷新页面',
                                type: 'error',
                                duration: 0,
                            });
                        }
                    }, 5000);
                };

                const stopTimer = () => {
                    if (intervalId.value) {
                        clearInterval(intervalId.value);
                        intervalId.value = null;
                    }
                };


                return {
                    Position,
                    FullScreen,
                    User,
                    Setting,
                    MoonNight,
                    Sunny,
                    Bell,
                    Postcard,
                    Check,
                    Plus,
                    Minus,
                    Close,
                    Delete,
                    SwitchButton,
                    Lock,
                    CirclePlus,
                    More,
                    server,
                    nickname,
                    announcement,
                    message,
                    sendMessageMethod,
                    messageLog,
                    onlineUsers,
                    chatMessages,
                    dialogVisible,
                    fontSize,
                    roleName,
                    toUser,
                    toChannel,
                    isChatAllDot,
                    isChatPrivateDot,
                    isChatChannelDot,
                    isBeMuted,
                    dark,
                    loginForm,
                    someNickname,
                    ruleFormRef,
                    rules,
                    ruleFormRef_channel,
                    rules_channel,
                    hasMoreMessage,
                    channels,
                    channelForm,
                    channelDialogVisible,
                    hasJoinChannel,
                    intervalId,
                    openWebsocket,
                    closeWebsocket,
                    changeSendMessageMethod,
                    sendmessage,
                    getOnlineUsers,
                    selectAllMessage,
                    login,
                    sendCommand,
                    fullScreen,
                    startPublicChat,
                    startPrivateChat,
                    startChannelChat,
                    changeDark,
                    querySearch,
                    submitForm,
                    submitForm_channel,
                    logout,
                    seeMoreMessage,
                    getAllChannel,
                    addAChannel,
                    joinChannel,
                    exitChannel,
                    removeChannel,
                    startTimer,
                    stopTimer,

                };
            }
        }
    ;
    const app = Vue.createApp(App);
    app.use(ElementPlus);
    app.mount("#app");
</script>
</body>

</html>

